package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApUnlikeBehaviorService;
import com.heima.common.constans.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.UnLikeBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUnlikeBehaviorServiceImpl implements ApUnlikeBehaviorService {
    /**
     * 取消点赞
     *
     * @param dto
     * @return
     */
    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult unLikeBehavior(UnLikeBehaviorDto dto) {
        //1. 校验参数
        if (dto == null || !checkDtoParam(dto)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2. 判断用户是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3. 根据用户id和文章id查询点赞记录
        if (dto.getType() == 0) {
            cacheService.hPut(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString(), dto.toString());
        }else{
            //取消不喜欢按钮，删除不喜欢记录
            cacheService.hDelete(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

        /**
         * 参数校验
         *
         * @param dto
         * @return
         */
        private boolean checkDtoParam (UnLikeBehaviorDto dto){
            if (dto.getType() < 0 || dto.getType() > 1) {
                return false;
            }
            return true;
        }
    }
